﻿//上一条 add by zengtongchun 2016-05-06
function Prev() {
    var index = fnGetNowId(id, 0);
    index = index <= 0 ? 0 : index;
    var nowId = idArray[index];
    fnReplaceUrl(nowId);
}
//获取url地址截取id 　add by zengtongchun 2016-05-06
function fnReplaceUrl(changeId) {
    var url = window.location.href;
    var startIndex = url.indexOf("id") + 2;
    var endIndex = url.indexOf("isview") - 1;
    var url1 = url.substring(0, startIndex);
    var url2 = url.substring(endIndex, url.length);
    var nowUrl = url1 + "=" + changeId + url2;
    window.open(nowUrl, "_new");

}
//判断是否qp有上传或者下载成功过 add by zengtongchun 2016-08-30
function fnCheckQpRecord() {
    var exist = 0;
    if (mini.get("hidtransport_way").getValue() == "01") {
        return 1;
    }
    var qpData = fnGetData("v_t_mains_version_qpreturn", "t_main_id=" + id).data;
    if (qpData.length > 0) {
        exist = 1;
    }
    //for (var i = 0; i < qpData.data.length; i++) {
    //    if (($.trim(qpData[i].call_mother_name) == "qpreturn" || $.trim(qpData[i].call_mother_name) == "qpinput") && qpData[i].qp_status == "成功") {
    //        exist = 1;
    //        break;
    //    }
    //}
    return exist;
}
//下一条 add by zengtongchun 2016-05-06
function Next() {
    var index = fnGetNowId(id, 1);
    index = index > idArray.length - 1 ? idArray.length - 1 : index;
    var nowId = idArray[index];
    fnReplaceUrl(nowId);
}
//获取当前id上一条或者下一条的id
//nowId:当前id,prevOrNext:0上,1下
function fnGetNowId(nowId, prevOrNext) {
    var changeIndex = 0;
    for (var i = 0; i < idArray.length; i++) {
        if (idArray[i] == nowId) {
            changeIndex = prevOrNext == 0 ? i - 1 : i + 1;
            break;
        }
    }
    return changeIndex;
}
//校验除当前报关单外是否还存在相同自编号 add by zengtongchun 2016-06-18
function fnCheckUseNo() {
    var num = 0;
    var useNo = mini.get("txtSelfNumbering").getValue();
    var existUseNo = fnGetEntityInstance("t_mains", "self_numbering='" + useNo + "' and id<>" + id);
    if (existUseNo != null) {
        num = 1;
    }
    return num;
}
//海关查验信息
function fnHaiGuanCheck(checkstatusesdata) {
    //给海关查柜，商检查柜赋值
    checkstatusesdata.check_yn = checkstatusesdata.check_yn == "true" ? 1 : 0;
    checkstatusesdata.check01_yn = checkstatusesdata.check01_yn == "true" ? 1 : 0;
    //沟了海关查柜

    if (checkstatusesdata.check_yn == 1 && checkstatusesdata.check_id == "" && checkstatusesdata.check_org_id == "") {
        checkstatusesdata.check_id = empId;
        checkstatusesdata.check_org_id = deptOrgId;
    }
    //取消勾选
    if (checkstatusesdata.check_yn == 0 && checkstatusesdata.check_id != "" && checkstatusesdata.check_org_id != "") {
        checkstatusesdata.check_id = "";
        checkstatusesdata.check_org_id = "";

    }
    //沟了商检查柜
    if (checkstatusesdata.check01_yn == 1 && checkstatusesdata.check01_id == "" && checkstatusesdata.check_org01_id == "") {
        checkstatusesdata.check01_id = empId;
        checkstatusesdata.check_org01_id = deptOrgId;
    }
    //取消勾选
    if (checkstatusesdata.check01_yn == 0 && checkstatusesdata.check01_id != "" && checkstatusesdata.check_org01_id != "") {

        checkstatusesdata.check01_id = "";
        checkstatusesdata.check_org01_id = "";
    }
    return checkstatusesdata;
}

function fnSaveCommonData() {
   
    var usenoobj = mini.get("txtSelfNumbering");
    var useno = usenoobj.getValue();
    if (useno != "") {
        var chk = fnCheckUseNo();
        if (chk > 0) {
            mini.alert("自编号重复，请重新获取!", "提示信息", function () {
                usenoobj.focus();
                usenoobj.setValue("");
            });
            //mini.get("btnsave").setenabled(true);
            return;
        }


    }
    mini.get("btnQpDownload").setEnabled(false);//先禁止掉下载按钮。
    //mini.get("btnSave").setEnabled(false);//先禁止掉下载按钮。
    //  UpdateGoodsfinal_country_no(); //原产国默认显示中国
    SetGoodsNum();
    SetContainerCount();
    var form = new mini.Form("#form1");
    var grid = mini.get("datagrid1");
    form.validate();
    if (!form.isValid()) return;
    var form_data = form.getData();
    form_data.self_numbering = form_data.self_numbering.replace("S", "").replace("s", "");
    if (form_data.id == "")
        form_data.id = mini.get("id").getValue();
    var maindata = mini.clone(form_data);
    if (typeof (maindata) != "undefined" && maindata != null) {
        var id = mini.get("id").getValue();
        /*****************生成 报关单信息 begin***********************/
        //maindata.receive_dt=mini.formatDate(new Date(),"yyyy-MM-dd HH:mm:ss" );
        var mainextsdata = mini.clone(maindata);
        mainextsdata.t_main_id = id;
        delete mainextsdata.id;

        //海运进出口时出口口岸前海港区默认给申报现场为蛇口海关 add by zengtongchun 2015-01-14
        if ((maindata.port_no == "5349") && (maindata.declare_id == 1 || maindata.declare_id == 2) && maindata.transport_way == "01") {
            mainextsdata.apply_port_no = "5304";
        }
        //保存报关单时去查询是否存在统一编号了
        if ($.trim(maindata.unify_no) == "") {
            var data = fnGetData("t_apply_no_status_call_log", "t_main_id=" + id, "id", "Yes");
            if (data != null && data.data.length > 0) {
                maindata.unify_no = data.data[0].SeqNo;
            }
        }


        /*****************生成 其他事项确认 begin***********************/
        var relationship_yn = maindata.relationship_yn;
        relationship_yn = relationship_yn == undefined ? 0 : relationship_yn;
        var price_yn = maindata.price_yn == 1 ? 1 : 0;
        var pay_yn = maindata.pay_yn;
        pay_yn = pay_yn == undefined ? 0 : pay_yn;
        var hidpromise_itmes = relationship_yn + '' + price_yn + '' + pay_yn;

        maindata.promise_itmes = hidpromise_itmes;
        /*****************生成 其他事项确认 end***********************/

        /*****************生成 报关单信息 end***********************/

        /*****************生成 集装箱信息 begin***********************/
        var data = grid.getChanges();
        data = addt_main_id(data, id);
        /*****************生成 集装箱信息 end***********************/

        /*****************生成海关查验信息 begin***********************/
        var checkstatusesdata = mini.clone(form_data);
        checkstatusesdata.t_main_id = id;
        var check_statusesid = mini.get("check_statusesid").getValue();
        checkstatusesdata.id = check_statusesid == undefined ? "0" : check_statusesid;
        checkstatusesdata = fnHaiGuanCheck(checkstatusesdata);
        /*****************生成海关查验信息 end***********************/

        maindata["complete_id"] = empId;//当前操作人。方便后台获取
        /*****************生成 商品表体 begin***********************/
        var grid2 = mini.get("datagrid2");
        var goodsdata = grid2.getChanges();
        //商品序号重复不允许上传
        var goodsNowData = grid2.getData();
        var goodsNowCount = Enumerable.From(goodsNowData).GroupBy("$.num_no").Count();
        if (goodsNowCount != goodsNowData.length) {
            mini.alert("商品序号存在重复的,请核实！");
            return;
        }
        
        goodsdata = addt_main_id(goodsdata, id);
        /*****************生成 商品表体 end***********************/

        /*****************生成 随附单据 begin***********************/
        var accompanydata = addt_main_id(accompany_details, id);
        /*****************生成 随附单据 end***********************/
        //通过随附单据的单证号给商检号赋值(在没有商检号的前提下)
        /*****************生成 流水号 begin***********************/

        /*****************非出口类型，不存在船代 Edit by zhuhy begin 2015-06-30 begin***********************/
        var ship_agent_id;//船代id
        var ship_agent_name;//船代名称
        var shipping_no = "";//流水号
        var cabinNo = "";   //提运单号
        var grid6 = mini.get("datagrid6");
        if (grid6 != null) {
            var shippingNoData = grid6.getData();
            var count = Enumerable.From(shippingNoData).Count();//shipping_no
            var disCount = Enumerable.From(shippingNoData).Select("$.shipping_no").Distinct().Count();
            if (shippingNoData.length > 0 && (count != disCount)) {
                mini.alert("流水号列表重复,请核实！");
                return;
            }
        }

        var json7 = "[]";
        var shipdata = [];
        if (description == "Export" || description == "ExportTransit") {
            var shipping_dt = mini.formatDate(new Date(), "yyyy-MM-dd");
            ship_agent_id = mini.get("txtship_agent_id").getValue();//船代id
            ship_agent_name = mini.get("txtship_agent_id").getText();//船代名称
            shipping_no = mini.get("txtserial_no").getValue();//流水号
            cabinNo = mini.get("txtcabin_no").getValue();//提运单号

            var str = "";
            if (grid6.data.length == 1) {
                for (var i = 0; i < grid6.data.length; i++) {
                    str += grid6.data[i].shipping_no;
                }
                if (str != shipping_no || str != cabinNo) {
                    mini.alert("【流水号】【提运单号】【右边流水号】不一致 】保存失败！");
                    return false;
                }
            }

            if (shipping_no != "" && grid6.data.length == 0) {
                var count = fnCheckShippingNo(shipping_no, id);
                if (count==0) {
                    json7 = "{\"id\":'',\"t_main_id\":" + id + ",\"ship_agent_id\":" + ship_agent_id + ",\"ship_agent_name\":\"" + ship_agent_name + "\",\"shipping_no\":\"" + shipping_no + "\",\"zc_yn\":1,\"shipping_dt\":\"" + shipping_dt + "\"}";
                    shipdata = mini.decode(json7);
                }
                
            } else {
                json7 = mini.encode(grid6.getChanges());
                shipdata = grid6.getChanges();
            }
        }
        /*****************非出口类型，不存在船代 Edit by zhuhy end 2015-06-30 end***********************/
        /*****************生成 流水号 end***********************/

        ////报关整理单人 add by zengtongchun 2015-10-19
        var prefix = mini.get("hidtransport_way").getValue();//获取海陆空类型
        //qp类型判断
        if (prefix == "03") {//空运(进口是进口出口是出口，运输工具第一位是@并且是出口就是出口转关，运输工具第一位@口岸是5197类型是进口就是进口转关)
            var transPrefix = "";
            var transName = maindata.transname;//运输工具编号
            if (transName.length > 1) {
                transPrefix = transName.substr(0, 1);
            }
            var qpType = 0;//默认0 进口
            if (maindata.declare_id == 1) {//出口
                qpType = 1;
            }
            if (maindata.declare_id == 1 && transPrefix == "@") {//出口转关
                qpType = 3;
            }
            if (maindata.declare_id == 2 && transPrefix == "@") {//进口转关
                qpType = 2;
            }
            maindata.send_no = qpType;

        }

        if (prefix == "02") {  // 陆运  add by zhongxx 2016-10-13
            var chkqbYnData = mini.get("chkqb_yn").getValue(); //确报状态
            var operData = fnGetSingleData('t_mains_operator', " t_main_id='" + id + "' and operator_type=115");// 确报取消 保存时间 去掉人
            if (operData != null) {
                if (chkqbYnData == 0) {  //确报 取消  去掉人
                    operData[0].operator = "";
                } else {
                    operData[0].operator = empId;
                    operData[0].operator_dt = "";
                }
                fnSaveData('t_mains_operator', operData, '');// 确报取消 保存 去掉人
            }

        }

        var processdata = mini.get("dataProcessInfo1").data;
        var zhengliprocess = Enumerable.From(processdata).Where(function (x) { return x.operator_name == "整理" }).ToArray()[0];


        //整理 zhengliprocess.operator_dt  华为接口过来的数据默认没有整理人
        if (form_data.bill_no.length <= 0 || zhengliprocess.operator_dt == null) {
            var type = 2;

            if (prefix == "02") {
                type = 101;
            }
            if (prefix == "03") {//空运
                type = 201;
            }

            var operator = [{ id: '', t_main_id: form_data.id, operator: empId, operator_type: type }];
            fnSaveData('t_mains_operator', operator, '');// 操作记录

        }

        //报关单制单人 add by zengtongchun 2016-05-11 谁填监管方式就是谁
        if (form_data.trade_no != "") {
            var existZhiDanInfo = SetZhiDan();
            var type = 1;//默认海运
            if (prefix == "02") {//陆运
                type = 102;
            }
            if (prefix == "03") {//空运
                type = 202;
            }
            //没数据才添加
            if (existZhiDanInfo == 0) {
                var operator = [{ id: '', t_main_id: form_data.id, operator: empId, operator_type: type }];
                fnSaveData('t_mains_operator', operator, '');// 操作记录
            }

        }

        if (form_data.complete_yn == "1") {//交单时
            var mainsData = fnGetEntityInstance("v_t_mains", "id=" + id);
            if (mainsData == null) {
                mini.alert("请先保存,在勾换票！");
                return;
            }
            var delPayFees = fnGetData("t_mains_pay_fees", "t_main_id=" + id).data;
            if (delPayFees.length <= 0) {
                GetFeesList(id);//先加载费用列表
                var payFees = GetPayCost();//获取报关单费用支出项
                fnSaveData('t_mains_pay_fees', payFees, '');//报关单费用支出表
            }
        }
        //交单校验码头是盐田的有扣留状态口岸业务除外的
        var kou_status = CheckKouLiu();
        if (form_data.complete_yn == "1" && form_data.wharf_id == 11189 && kou_status == 1 && (declareId == 1 || declareId == 3 || declareId == 5)) {
            mini.alert("扣留状态不为VM或者N/A不能交单！");
            return;
        }
        //删除进程信息
        var delProcessInfo = DelProcessInfo();
        if (delProcessInfo.length > 0) {
            fnSaveData('t_mains_operator', delProcessInfo, 'delete');// 删除交单记录
        }
        if (form_data.complete_yn == "0") {
            var delPayFees1 = fnGetData("t_mains_pay_fees", "t_main_id=" + id).data;
            if (delPayFees1.length > 0) {
                fnSaveData('t_mains_pay_fees', delPayFees1, 'delete');// 删除报关单费用
            }
        }
        //外勤录入改船费，进口换单费
        addCost = addt_main_id(addCost, id);
        if (mainextsdata.jkhd_by == "") {
            for (i = 0; i < addCost.length; i++) {
                if ((addCost[i].fee_cd == "jkhd_cost" || addCost[i].fee_cd == "gc_cost") && addCost[i].cost > 0) {
                    mainextsdata.jkhd_by = empId;
                    mainextsdata.jkhd_org_id = deptOrgId;
                    break;
                }
            }
        }
        var deatilsdata = grid.getData();

        //空运交单时，校验集装箱数与集装箱表体数
        if (prefix == "03" && maindata.complete_yn == 1 && deatilsdata.length != maindata.container_count) {
            mini.alert("集装箱数与集装箱表体数不一致！不能交单,请核实！");
            return;
        }
        var lyCheck = 0;//陆运校验必须有柜号才能保存
        if (maindata.transport_way == "02") {
            var containerNo = "";
            if (deatilsdata.length > 0) {
                containerNo = deatilsdata[0].container_no;
            }
            if (containerNo == "") {
                lyCheck = 1;
                if (confirm("默认必须有柜号，是否自动添加一个虚拟柜号？")) {
                    if (deatilsdata.length == 0) {
                        var defaultContainerInfo = { id: "0", num_no: "1", t_main_id: maindata.id, container_no: "LKDEFAULT", fee_yn: 1, container_type_no: "40", fee_type: "F" };
                        deatilsdata.push(defaultContainerInfo);
                    } else {
                        deatilsdata[0].container_no = "LKDEFAULT";
                        deatilsdata[0].fee_yn = 1;
                        deatilsdata[0].container_type_no = "40";
                        deatilsdata[0].fee_type = "F";
                    }
                    maindata.container_count = 1;
                    lyCheck = 0;
                }
            }

        }
        if (lyCheck == 1) {
            return;
        }
        //交单时，如果没有柜号默认给添加一个虚拟柜号 add by zengtongchun 2016-11-23
        if (maindata.complete_yn == 1 && deatilsdata.length == 0) {
            var defaultContainerInfo = { id: "0", num_no: "1", t_main_id: maindata.id, container_no: "LKDEFAULT", fee_yn: 1, container_type_no: "40", fee_type: "F" };
            deatilsdata.push(defaultContainerInfo);
            maindata.container_count = 1;
        }
        var mainsSplitData = fnSetMainsSplit(id, accompanydata);
        fnSaveData('t_mains', maindata, '');//主表
        fnSaveData('t_main_exts', mainextsdata, '');//扩展表
        fnSaveData('t_details', deatilsdata);//集装箱表
        fnSaveData('t_check_statuses', checkstatusesdata, '');// 查验信息
        fnSaveData('t_other_cost', addCost, '');// 费用信息
        fnSaveData('t_goods_details', goodsdata, '');// 商品信息
        fnSaveData('t_accompany_details', accompanydata, '');// 随附单据
        fnSaveData('t_shipping_details', shipdata, '');// 船代
        fnSaveData('t_mains_splits', mainsSplitData, '');// 分割表
        if (prefix == "02") {//陆运时
            description = description == "LandTransportationImport" ? "LandTransportationExport" : "LandTransportationExport"; //陆运进出口都进同一个check校验
        }
        if (prefix == "03") {//空运
            description = description == "AirTransportationImport" ? "AirTransportationExport" : "AirTransportationExport"; //空运进出口都进同一个check校验
        }
        //保存数据到数据库
        var checkclassname = description + "Check";//数据校验类
        if (maindata.id == 0 || maindata.declare_id == 11) {
            alert("id为0，请联系技术人员！");
            return;
        }

        fnDataSaveToDataBase(checkclassname, id);



        //刷新父窗口列表数据
        //  window.opener.location.reload();
        //window.opener.fnQuciklyQuery();
        //fnDataSaveToDataBase("");
    }
}

function fnCheckShippingNo(shippingNo, id) {
    var count = 0;
    var data = fnGetEntityInstance("t_shipping_details", "t_main_id=" + id + " and shipping_no='" + shippingNo + "'");
    if (data!=null) {
        count = 1;
    }
    return count;
}

function fnSetMainsSplit(t_main_id, accompanydata) {
    var goods = mini.get("datagrid2").getData();
    var details = mini.get("datagrid1").getData();
    var shipping = [];
    if (mini.get("datagrid6") != null) {
        shipping = mini.get("datagrid6").getData();
    }

    var goods_no = Enumerable.From(goods).Where(function (i) {
        return i.container_no != "LKDEFAULT";
    }).Select("$.goods_no").ToArray().join(",");
    var goods_spec = Enumerable.From(goods).Select("$.goods_spec").ToArray().join(",");
    var details_goods_name = Enumerable.From(goods).Select("$.goods_name").ToArray().join(",");
    var container_no1 = Enumerable.From(details).Select("$.container_no").ToArray().join(",");
    var serial_no = Enumerable.From(shipping).Select("$.shipping_no").ToArray().join(",");
    var sfdj_no = Enumerable.From(accompanydata).Select("$.accompany_no").ToArray().join(",");
    var currency_name = "";
    if (goods.length>0) {
        currency_name = goods[0].currency_name;
    }
    var hgdc_count = Enumerable.From(details).Count(function (i) {
        return i.hgtz_dt != "" && i.hgtz_dt!=null;
    });
    
    return { t_main_id: t_main_id, goods_no: goods_no, goods_spec: goods_spec, details_goods_name: details_goods_name, container_no1: container_no1, serial_no: serial_no, sfdj_no: sfdj_no, currency_name: currency_name, hgdc_count: hgdc_count };
}

//判定制单是否已经有记录了 add by zengtongchun 2016-05-11
function SetZhiDan() {
    var exist = 0;
    var processInfoData1 = mini.get("dataProcessInfo1").getData();
    var processInfoData2 = mini.get("dataProcessInfo2").getData();
    //合并进程信息
    var processInfoData = Enumerable.From(processInfoData1).Union(processInfoData2).ToArray();
    for (var i = 0; i < processInfoData.length; i++) {
        if (processInfoData[i].operator_name == "制单" && processInfoData[i].name != null) {
            exist = 1;
            break;
        }
    }
    return exist;
}
//验证扣留状态 add by zengtongchun 2016-05-13
function CheckKouLiu() {
    var exist = 0;
    var processInfoData1 = mini.get("dataProcessInfo1").getData();
    var processInfoData2 = mini.get("dataProcessInfo2").getData();
    //合并进程信息
    var processInfoData = Enumerable.From(processInfoData1).Union(processInfoData2).ToArray();
    for (var i = 0; i < processInfoData.length; i++) {
        //if (processInfoData[i].operator_name == "扣留状态" && processInfoData[i].operator_dt != "" && processInfoData[i].operator_dt != null && processInfoData[i].mark != "VM") {
        //    exist = 1;
        //    break;
        //}

        if (processInfoData[i].operator_name == "扣留状态" && !(processInfoData[i].mark == "VM" || processInfoData[i].mark == "N/A")) {
            exist = 1;
            break;
        }
    }
    return exist;
}

var DelProcessInfoArray = [{ id: 'chkcomplete_yn', name: '交单' },
{ id: 'chkchay_yn', name: '海关查验通知' },
{ id: 'chkpass_yn', name: '海关放行' },
{ id: 'chkzfh_yn', name: '总复核' },
{ id: 'chkbcd_yn', name: '编舱单' }
//{ id: 'chkqb_yn', name: '确报' }
];
//删除进程记录 add by zengtongchun 2016-03-28
function DelProcessInfo() {
    var delProcessInfo = [];
    var processInfoData1 = mini.get("dataProcessInfo1").getData();
    var processInfoData2 = mini.get("dataProcessInfo2").getData();
    //合并进程信息
    var processInfoData = Enumerable.From(processInfoData1).Union(processInfoData2).ToArray();
    for (var j = 0; j < DelProcessInfoArray.length; j++) {
        var obj = mini.get(DelProcessInfoArray[j].id);
        if (obj == null) {
            continue;
        }
        if (obj.getValue() == "0") {
            for (i = 0; i < processInfoData.length; i++) {
                if (processInfoData[i].operator_name == DelProcessInfoArray[j].name && processInfoData[i].operator_dt != "" && processInfoData[i].operator_dt != null) {
                    delProcessInfo.push(processInfoData[i]);
                    break;
                }
            }
        }
    }
    return delProcessInfo;

}
//根据进出口类型判断随度单据 通关单号 出口【代码】为B  进口代码为A
function SetShangJianNo(mains, comapnyNos) {
    for (var i = 0; i < comapnyNos.length; i++) {
        //出口
        if (mains.declare_id == 1 && comapnyNos[i].control_no.toUpperCase() == "B") {
            mains.sfdj_no = comapnyNos[i].accompany_no;
            break;
        }
        //进口
        if (mains.declare_id == 2 && comapnyNos[i].control_no.toUpperCase() == "A") {
            mains.sfdj_no = comapnyNos[i].accompany_no;
            break;
        }
    }
    return mains;
}
//继续新增时删除其余datagrid所有数据 add by zengtongchun 2016-08-11
function fnClearDataGrids() {
    var grids = ["datagrid2", "datagrid1", "datagrid6", "dataProcessInfo1", "dataProcessInfo2", "dataQpRecord", "dataLogicRecord", "datagrid3", "datagrid4"];
    for (var i = 0; i < grids.length; i++) {
        if (mini.get(grids[i]) != null) {
            mini.get(grids[i]).clearRows();
        }
    }
    //特殊处理其他费用
    for (var j = 0; j < addCost.length; j++) {
        addCost[j].id = 0;
    }
}

function fnContinueObj() {

    var customer = mini.get("autcustomer_name").getText();//客户名称
    var customer01 = mini.get("txtcustomer01_name").getValue();//第二客户名称
    var customerId = mini.get("hidcustomer_id").getValue();//客户编码
    var companyName = mini.get("deptidname");
    var company = companyName == null ? "" : companyName.getValue();//所属公司

    //陆运里面无  港建费客户 保安费客户 所以需要判断是否为空
    var autwharf_customer_name = mini.get("autwharf_customer_name");//港建费客户
    var wharf_customer_id = mini.get("wharf_customer_id");//港建费客户id
    var txtprotect_customer_name = mini.get("txtprotect_customer_name");//保安费客户
    var protect_customer_id = mini.get("protect_customer_id");//保安费客户id
    var wharfCustomerName = autwharf_customer_name == null ? "" : autwharf_customer_name.getText();//港建费客户
    var wharfCustomerId = wharf_customer_id == null ? "" : wharf_customer_id.getValue();//港建费客户id
    var protectCustomerName = txtprotect_customer_name == null ? "" : txtprotect_customer_name.getValue();//保安费客户
    var protectCustomerId = protect_customer_id == null ? "" : protect_customer_id.getValue();//保安费客户id
    var drawback_dt = mini.get("txtdrawback_dt").getValue();

    var portName = mini.get("autport_name").getText();//口岸名称
    var portNo = mini.get("txtport_no").getValue();//口岸编码
    var shenPortName = mini.get("autapply_port_no").getText();//申报现场
    var shenPortNo = mini.get("autapply_port_no").getValue();//申报现场值
    var shipperName = mini.get("autshipper_name").getText();//经营单位名称
    var shipperNo = mini.get("txtshipper_no").getValue();//经营单位编码
    //  var consigneeName = mini.get("autconsignee_name").getText();//发货单位名称
    var consigneeName = mini.get("autconsignee_name").getValue();//发货单位名称

    var consigneeNo = mini.get("txtconsignee_no").getValue();//发货单位编码
    var declareId = mini.get("hiddeclare_id").getValue();
    var org_id = mini.get("txtHidOrgId").getValue();//组织机构代码
    var prefix = mini.get("hidPrefix").getValue();
    var transport_way = mini.get("hidtransport_way").getValue();
    var isContinueObj = {
        id: 0,
        prefix: prefix,
        transport_way: transport_way,
        customer_name: customer,
        customer01_name: customer01,
        customer_id: customerId,
        deptidname: company,
        wharf_customer_name: wharfCustomerName,
        wharf_customer_id: wharfCustomerId,
        protect_customer_name: protectCustomerName,
        protect_customer_id: protectCustomerId,
        port_name: portName,
        port_no: portNo,
        apply_port_name: shenPortName,
        apply_port_no: shenPortNo,
        shipper_name: shipperName,
        drawback_dt: drawback_dt,
        shipper_no: shipperNo,
        consignee_name: consigneeName,
        consignee_no: consigneeNo,
        org_id: org_id,
        declare_id: declareId
    };
    fnClearDataGrids();
    return isContinueObj;
}
//继续新增 add by zengtongchun 2016-03-08

function fnContinueAdd() {
    isContinue = 1;
    SetData({ id: id });
}
//获得当前报关单是否存在整理人 add by zengtongchun 2015-10-19
function GetOperator(id) {
    var data = fnGetData("t_mains_operator", "t_main_id=" + id + " and operator_type=2").data[0];
    //存在
    if (data != null) {
        return 1;
    }
    //不存在
    return 0;
}
/**********************************
* add by zengtongchun 2015-10-20 保存前给报关单的商品数赋值
**************************************/
function SetGoodsNum() {
    var num = mini.get("datagrid2").data.length;
    mini.get("txtnum_goods").setValue(num);
}
/**********************************
* add by zengtongchun 2015-10-26 保存前给报关单的集装箱数赋值
**************************************/
function SetContainerCount() {
    var num = mini.get("datagrid1").data.length;
    mini.get("txtcontainer_count").setValue(num);
}
/**********************************
* add by zengtongchun 2016-07-12 逻辑审核错误信息记录
**************************************/
function AddLogicErrorMsg(type, msg) {
    $.ajax({
        url: "AddLogicErrorMsg",
        type: "post",
        data: { id: id, type: type, msg: msg },
        cache: false,
        success: function (text) {

        },
        error: function (jqXHR, textStatus, errorThrown) {

        }
    }
    );
}
/**********************************
* add by zhanyong 2015-05-16 逻辑审核
**************************************/

function fnLogic() {
    // var json = {id:};
    var id = mini.get("id").getValue();

    mini.mask({
        el: document.body,
        cls: 'mini-mask-loading',
        html: '加载中...'
    });

    var prefix = mini.get("hidtransport_way").getValue();
    $.ajax({
        url: "LogicCheck",
        type: "post",
        data: { id: id, prefix: prefix },
        cache: false,
        success: function (text) {
            mini.unmask(document.body);
            if (text == null || text == "" || text.length == 0) {
                mini.alert("校验成功！");
                AddLogicErrorMsg(0, "校验成功");
                return;
            }
            AddLogicErrorMsg(0, text);
            var textArray = text.split('<br>');
            var textData = "";
            for (var i = 0; i < textArray.length - 1; i++) {
                textData += (i + 1) + "、" + textArray[i] + "<br>";
            }
            var textList = "<table> <tr> <td style='color: red' >" + textData + "</td> </tr> </table>";
            mini.showMessageBox({
                showModal: false,
                width: 600,
                height: 1200,
                title: "提示！",
                message: textList,
                buttons: ["ok"],
                iconCls: "mini-messagebox-ok",
                html: textList
            });

        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert("Error" + jqXHR.responseText);
        }
    });
}
/**********************************
* add by zengtongchun 2016-11-14 接口QP上传
**************************************/
function fnNewQpInput1() {
    var id = mini.get("id").getValue();
    if (id == null || id == "") {
        mini.alert("请先保存报关单");
        return false;
    }
    var data = fnGetData("t_apply_no_status_call_log", "t_main_id=" + id, "id desc").data;
    var exist = 0;
    for (var i = 0; i < data.length; i++) {
        if (data[i].status == null || data[i].status == "") {
            exist = 1;
            break;
        }
    }
    if (exist == 1) {
        mini.alert("最新发送单还未返回数据！请稍后");
        return;
    }
    window.open("/extendpage/action/dataaction.aspx?action=getReportFile&type=report&order_no=" + id);
}

function fnNewQpInputCheck() {
    var msg = "";
    var mark = mini.get("txtmark").getValue();
    var contract_no = mini.get("txtcontract_no").getValue();
    var freight = mini.get("txtfreight").getValue();//运费
    var subscribe = mini.get("txtsubscribe").getValue();//保费
    var incidental = mini.get("txtincidental").getValue();//杂费
    if (mark.length > 70) {
        msg += "接口目前只支持70位以内的标记唛码<br>";
    }
    //if (/[!~@#$&%]+/.test(contract_no)) {
    //    msg += "合同协议号不能存在特殊字符<br>";
    //}
    if (freight.indexOf(".") > 1) {
        msg += "运费不能有小数<br>";
    }
    if (subscribe.indexOf(".") > 1) {
        msg += "保费不能有小数<br>";
    }
    if (incidental.indexOf(".") > 1) {
        msg += "杂费不能有小数<br>";
    }
    //msg += fnCheckGoodsSpec();
    //msg += fnAccompanyNo();

    return msg;
}
//运保费为率的情况只能为两位小数
function fnNewQpInputCheckNew() {
    var msg = "";
    var freightmode_no = mini.get("autfreightmode_no").getValue();
    var subscribemode_no = mini.get("autsubscribemode_no").getValue();
    var incidentalmode_no = mini.get("autincidentalmode_no").getValue();

    //var mark = mini.get("txtmark").getValue();
    var contract_no = mini.get("txtcontract_no").getValue();
    var freight = mini.get("txtfreight").getValue();//运费
    var subscribe = mini.get("txtsubscribe").getValue();//保费
    var incidental = mini.get("txtincidental").getValue();//杂费
    //if (mark.length > 70) {
    //    msg += "接口目前只支持70位以内的标记唛码<br>";
    //}
    if (freight.indexOf(".") > -1 && freightmode_no == 1) {
        if (freight.toString().split(".")[1].length > 2)
            msg += "运费为率不能有两位以上的小数<br>";
    }
    if (subscribe.indexOf(".") > -1 && subscribemode_no == 1) {
        if (subscribe.toString().split(".")[1].length > 2)
            msg += "保费为率不能有两位以上的小数<br>";
    }
    if (incidental.indexOf(".") > -1 && incidentalmode_no == 1) {

        if (incidental.toString().split(".")[1].length > 2)
            msg += "杂费为率不能有两位以上的小数<br>";
    }


    //msg += fnCheckGoodsSpec();
    //msg += fnAccompanyNo();


    return msg;
}


//校验商品规格不能有-字母 add by zengtongchun 2016-11-22
function fnCheckGoodsSpec() {
    var msg = "";
    var goodslist = mini.get("datagrid2").getData();
    for (var i = 0; i < goodslist.length; i++) {
        if (/[!~-]+[A-Za-z]/.test(goodslist[i].goods_spec)) {
            msg += "商品第" + goodslist[i].num_no + "项规格有-字母<br>";
        }
        if (/[!~&]+/.test(goodslist[i].goods_spec)) {
            msg += "商品第" + goodslist[i].num_no + "项规格有特殊符号'&'<br>";
        }
    }
    return msg;
}
//校验随附单据不能有-字母 add by zengtongchun 2016-11-22
function fnAccompanyNo() {
    var msg = "";
    for (var i = 0; i < accompany_details.length; i++) {
        if (/[!~-]+[A-Za-z]/.test(accompany_details[i].accompany_no)) {
            msg += "随附单据中存在-字母";
            break;
        }
    }
    return msg;
}

/**********************************
* add by houwei 2016-11-14 接口QP上传
**************************************/
function fnNewQpInput() {
    var id = mini.get("id").getValue();
    if (id == null || id == "") {
        mini.alert("请先保存报关单");
        return;
    }
    var msg = fnNewQpInputCheckNew();
    if (msg != "") {
        mini.alert(msg);
        return;
    }
    var data = fnGetData("t_mains_operator", "(operator_type=5 or operator_type=104 or operator_type=203) and t_main_id=" + id);
    if (data.data.length == 0) {
        mini.alert("请先逻辑审核");
        return;
    }
    var data = fnGetData("t_apply_no_status_call_log", "t_main_id=" + id, "id desc").data;
    var exist = 0;
    for (var i = 0; i < data.length; i++) {
        if (data[i].status == null || data[i].status == "") {
            exist = 1;
            break;
        }
    }
    if (exist == 1) {
        mini.alert("最新发送单还未返回数据！请稍后");
        return;
    }
    var messageid = mini.loading("正在上传中...", "正在上传");
    $.ajax({
        url: "QpInputNew",
        type: "get",
        async: true,
        timeout: 30000,
        data: { id: id },
        cache: false,
        success: function (text) {
            //result = text;
            //var json = mini.decode(result);
            //var status = json.STATUS;
            //if (status == 1) {
            //mini.unmask(document.body);
            mini.hideMessageBox(messageid);
            mini.showMessageBox({
                showModal: false,
                width: 250,
                title: "",
                message: "上传成功",
                buttons: [],
                iconCls: "mini-messagebox-ok",
                timeout: 1000
            });
            SetData({ id: id });
        },
        error: function (jqXHR, textStatus, errorThrown) {

            alert(jqXHR.responseText);
            mini.hideMessageBox(messageid);
        }

    });

}

/**********************************
* add by zhanyong 2015-05-29 上传QP
**************************************/
function fnQpInput() {
    if (GetQPConfigExist() == "") {
        mini.alert("未配置qp操作权限！");
        return;
    }
    var id = mini.get("id").getValue();
    if (id == null || id == "") {
        mini.alert("请先保存报关单");
        return false;
    }
    var data = fnGetData("t_mains_operator", "(operator_type=5 or operator_type=104) and t_main_id=" + id);

    if (data.data.length == 0) {
        mini.alert("请先逻辑审核");
        return false;
    }
    //mini.mask({
    //    el: document.body,
    //    cls: 'mini-mask-loading',
    //    html: '正在玩命上传中...'
    //});

    var messageid = mini.loading("正在上传中...", "正在上传");
    $.ajax({
        url: "QpInput",
        type: "get",
        async: true,
        timeout: 30000,
        data: { id: id },
        cache: false,
        success: function (text) {
            result = text;
            var json = mini.decode(result);
            var message = json.SEQNO;
            var status = json.STATUS;
            if (status == 1) {
                //mini.unmask(document.body);
                mini.hideMessageBox(messageid);
                mini.get("txtunify_no").setValue(message);
                mini.get("txteqp_dt").setValue(new Date());
                mini.showMessageBox({
                    showModal: false,
                    width: 250,
                    title: "上传成功",
                    message: message,
                    buttons: [],
                    iconCls: "mini-messagebox-ok",
                    timeout: 1000
                });

                var existCount = fnCheckUnifyNo(message);
                if (existCount > 0) {
                    mini.showMessageBox({
                        showModal: false,
                        width: 250,
                        title: "当前统一编号已重复存在,请核实！",
                        message: message,
                        buttons: [],
                        iconCls: "mini-messagebox-ok",
                        timeout: 2000
                    });

                }


            } else {
                AddLogicErrorMsg(1, message);
                mini.hideMessageBox(messageid);
                //mini.unmask(document.body);

                //var textArray = text.split('<br>');
                //var textData = "";
                //for (var i = 0; i < textArray.length - 1; i++) {
                //    textData += (i + 1) + "、" + textArray[i] + "<br>";
                //}
                //var textList = "<table> <tr> <td style='color: red' >" + textData + "</td> </tr> </table>";
                mini.hideMessageBox(messageid);
                mini.showMessageBox({
                    showModal: false,
                    width: 500,
                    height: 250,
                    title: "上传失败",
                    message: message,
                    buttons: ["ok"],
                    iconCls: "mini-messagebox-ok",

                });
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {


            if (textStatus === "timeout") {
                mini.alert("QP繁忙请稍后再试");
            } else {
                alert(jqXHR.responseText);
            }
            mini.hideMessageBox(messageid);
        }
    });
}
//qp上传成功后 校验统一编号是否重复 add by zengtongchun 2016-06-21
function fnCheckUnifyNo(unifyNo) {
    var exist = 0;
    var data = fnGetEntityInstance("t_mains", "unify_no='" + unifyNo + "' and id<>" + id);
    if (data != null) {
        exist = 1;
    }
    return exist;
}
/**********************************
* add by zengtongchun 2016-02-27  打开商品信息导入窗口
**************************************/
function GoodsExport(className, self) {
    var text = "";
    if (self != null && self != "") {
        text = self.defaultText;
    }
    var transport = mini.get("hidtransport_way").getValue();
    mini.open({
        url: "GoodsExport",        //页面地址
        title: "商品信息导入",      //标题.
        allowResize: false,
        allowDrag: true,
        width: 350,      //宽度
        height: 120,     //高度
        onload: function () {       //弹出页面加载完成
            var iframe = this.getIFrameEl();
            var data = { className: className, transport: transport };
            ////调用弹出页面方法进行初始化
            iframe.contentWindow.SetData(data);

        },
        ondestroy: function (action) {  //弹出页面关闭前
            if (action == "ok") {
                var iframe = this.getIFrameEl();
                //获取选中、编辑的结果
                var exportData = iframe.contentWindow.GetData();

                var code = exportData.code;//后端返回的单据字符串A,B...
                if (code != "" && code != undefined) {
                    var addcontrolNos = GetAccompanyDetails(accompany_details, code, declareId);
                    SetAccompanyDetails(addcontrolNos);
                }
                if (exportData.msg != null && exportData.msg != "") {
                    mini.alert(exportData.msg);
                }
                var goodsData = mini.decode(exportData.goodsInfo);    //必须。克隆数据。

                var detailsData = mini.decode(exportData.detailsInfo);    // 集装箱信息 必须。克隆数据。
                //&& detailsData.length>0
                if (detailsData != undefined && detailsData.length > 0) {
                    SetDetailsImportExcelInfo(detailsData);
                } else {
                    if (mini.get("hidtransport_way").getValue() == "02") {
                        var detailslists = mini.get("datagrid1"); //集装箱信息
                        var rows = detailslists.data;
                        if (rows.length > 0) {
                            if (rows[0].container_no != "LKDEFAULT") {
                                fnSaveData("t_details", rows, "delete");
                                detailslists.clearRows();
                                fnLYAddContainerInfo();
                            }

                        }

                    }
                }
                var mains = mini.decode(exportData.mainsInfo);
                if (mains != "") {
                    SetImportExcelInfo(mains, goodsData);

                    //if (mains.Msg!="") {
                    //    mini.alert(mains.Msg);
                    //}
                }
                goodsData = fnSetGoodsClearZero(goodsData);
                SetGoodsExportData(goodsData);
                var tab = mini.get("tabs2");
                var tabObj = tab.getTab(1);
                tab.activeTab(tabObj);
            }
        }

    });
    fnSetCookie("exportText", className, text);
}
//导入后商品数量清零处理 ztc 2016-08-18
function fnSetGoodsClearZero(goodsData) {
    for (var i = 0; i < goodsData.length; i++) {
        if (goodsData[i].amount == 0) {
            goodsData[i].amount = "";
        }
        if (goodsData[i].amount02 == 0) {
            goodsData[i].amount02 = "";
        }
        if (goodsData[i].amount03 == 0) {
            goodsData[i].amount03 = "";
        }
    }
    return goodsData;
}
//隐藏域值替换 add by zengtongchun 2016-04-13
function SetImportExcelInfo(importMainsInfo, goodsData) {

    var form = new mini.Form("#form1");
    var oldForm = form.getData();
    if (oldForm.transport_way == "02") {
        if (importMainsInfo.shipper_no == "4403061874") {  //陆运  联洲技术有限公司  
            oldForm.bus_no = importMainsInfo.bus_no;
        }

    }
    importMainsInfo = NotCover(importMainsInfo);
    importMainsInfo.org_id = oldForm.org_id;//组织机构
    importMainsInfo.id = oldForm.id; //id
    if (oldForm.transport_way == "02") {

        if (importMainsInfo.shipper_no == "4403061874" && goodsData != undefined) {  //陆运  联洲技术有限公司
            importMainsInfo.start_country_name = goodsData[0].country_no + "/" + goodsData[0].country_name; //运抵国(地区)
            importMainsInfo.start_country_no = goodsData[0].country_no;
            importMainsInfo.loadport_name = goodsData[0].country_no + "/" + goodsData[0].country_name; //指运港
            importMainsInfo.loadport_no = goodsData[0].country_no;
            importMainsInfo.cust_linkman = "陈李";
            importMainsInfo.bus_no = oldForm.bus_no;
        }

        importMainsInfo.container_count = oldForm.container_count;
        importMainsInfo.port_name = oldForm.port_name;
        importMainsInfo.port_no = oldForm.port_no;
        importMainsInfo.apply_port_no = oldForm.apply_port_no;
        importMainsInfo.apply_port_name = oldForm.apply_port_name;
    }
    if (oldForm.transport_way == "01") {
        importMainsInfo.shipper_no = oldForm.shipper_no;
        importMainsInfo.shipper_name = oldForm.shipper_name;
        importMainsInfo.consignee_no = oldForm.consignee_no;
        importMainsInfo.consignee_name = oldForm.consignee_name;
        importMainsInfo.port_name = oldForm.port_name;
        importMainsInfo.port_no = oldForm.port_no;
        importMainsInfo.apply_port_no = oldForm.apply_port_no;
        importMainsInfo.apply_port_name = oldForm.apply_port_name;
        importMainsInfo.promise_itmes = oldForm.promise_itmes;
    }

    importMainsInfo.transport_way = oldForm.transport_way;//海陆空类型
    importMainsInfo.prefix = oldForm.prefix;//自编号前缀
    importMainsInfo.entryport_type_id = oldForm.entryport_type_id;
    importMainsInfo.declare_id = oldForm.declare_id;//报关类型
    importMainsInfo.bill_no = oldForm.bill_no;//工作号
    importMainsInfo.transmode_name = oldForm.transmode_name;//运输方式
    importMainsInfo.entry_typename = oldForm.entry_typename;//报关单类型
    importMainsInfo.transmode_no = oldForm.transmode_no;//运输方式
    importMainsInfo.entry_type = oldForm.entry_type;//报关单类型
    form.setData(importMainsInfo);

    if (importMainsInfo.promise_itmes != null && importMainsInfo.promise_itmes.length >= 3) {
        var relationship_yn = importMainsInfo.promise_itmes.substr(0, 1);
        var price_yn = importMainsInfo.promise_itmes.substr(1, 1);
        var pay_yn = importMainsInfo.promise_itmes.substr(2, 1);
        mini.get("cobrelationship_yn").setValue(relationship_yn); //特殊关系确认
        mini.get("chkPrice").setValue(price_yn); //价格影响确认
        mini.get("cobpay_yn").setValue(pay_yn);   //支付特许权使用费确认
    }
}
//不覆盖报关单表头 add by zengtongchun 2016-04-18
function NotCover(nowMains) {
    var array = $("#mains").find("input");
    var form = new mini.Form("#form1");
    var oldForm = form.getData();
    for (var item in oldForm) {
        for (var i = 0; i < array.length; i++) {
            if ($(array[i]).attr("name") != null) {
                if (item == $(array[i]).attr("name") && item != "drawback_dt" && item != "voyage" && item != "bus_no") {
                    nowMains["" + item + ""] = oldForm[item];
                    break;
                }
            }
        }
    }
    return nowMains;
}

// add by zengtongchun 向已有商品随附单据集合里面添加数据 2016-03-03
function SetAccompanyDetails(addcontrolNos) {
    //往 datagrid2 随附单据表里面添加新行
    Enumerable.From(addcontrolNos).ForEach(function (x) {
        var newRow = { id: '', control_no: x, accompany_no: '' };
        accompany_details.push(newRow);
    });
    SetCheckNo(accompany_details);

}
//给导入后的商品信息赋值 add by zengtongchun 2016-02-27
function SetGoodsExportData(exportData) {
    var goodlists = mini.get("datagrid2");
    removeOldGoods();
    exportData = SetGoodsOtherInfo(exportData);
    goodlists.addRows(exportData);
}

//给导入后的集装箱信息赋值 add by zhongxx 2016-08-12
function SetDetailsImportExcelInfo(detailsData) {
    var detailslists = mini.get("datagrid1"); //集装箱信息
    var rows = detailslists.data;
    if (rows.length > 0) {
        fnSaveData("t_details", rows, "delete");
        detailslists.clearRows();
    }
    detailslists.addRows(detailsData);
}

//重新给序号排序并添加t_main_id add by zengtongchun 2016-02-27
function SetGoodsOtherInfo(exportData) {
    var datas = 0;
    for (var i = 0; i < exportData.length; i++) {
        datas++;
        exportData[i].num_no = datas;
        exportData[i].t_main_id = id;
        if (exportData[i].goods_no == "") {
            exportData.remove(exportData[i]);
        }
    }
    return exportData;
}

/**********************************
   * add by zhanyong 2015-05-05  删除商品信息
   **************************************/
function removeOldGoods() {
    var grid2 = mini.get("datagrid2");
    var rows = grid2.data;
    if (rows.length > 0) {
        fnSaveData("t_goods_details", rows, "delete");
        grid2.clearRows();
    }
}

/**********************************
* add by zhanyong 2015-06-06 QP下载
**************************************/
function fnQpDownLoad() {
    //var records_no = mini.get("txtrecords_no").getValue();
    ////海运未填写备案号不允许下载
    //if ($.trim(records_no).length<=0&&mini.get("hidtransport_way").getValue()=="01") {
    //    mini.alert("未填写备案号不允许下载！");
    //    return;
    //}
    var id = mini.get("id").getValue();
    var shipper_name = mini.get("autshipper_name").getText();
    var shipper_no = mini.get("txtshipper_no").getValue();
    //var auttrade_no = mini.get("auttrade_no").getValue();
    //
    var auttrade_no = "";
    var data = fnGetData("t_mains", "id=" + id);
    if (data != null && data.data.length > 0) {
        auttrade_no = data.data[0].trade_no;
        //console.log(auttrade_no);
    }
    //
    if (auttrade_no == '0110') {
        mini.alert("一般贸易不能下载！");
        return;
    }

    if (GetQPConfigExist() == "") {
        mini.alert("未配置qp操作权限！");
        return;
    }
    var data = fnGetData("v_data_base_dictionary_detail", "code='bg_download_switch'").data;
    var isDownload = data[0].value.split(",");
    var busType = mini.get("hidtransport_way").getValue();
    var count = Enumerable.From(isDownload).Count(function (i) {
        return i == busType;
    });
    if (count == 0) {
        var companies = fnGetEntityInstance("t_base_companies", "znamec='" + shipper_name + "' and zucode='" + shipper_no + "'");
        if (companies == null) {
            mini.alert("不在设定范围内,不允许下载！");
            return;
        }
        if (companies.isDownload != 1) {
            mini.alert("不在设定范围内,不允许下载！");
            return;
        }
    }
    if (fnGetQpDownloadCount(id) >= 2) {
        mini.alert("非常抱歉,2次下载次数已用完！");
        return;
    }
    if (id == null || id == "") {
        mini.alert("请先保存报关单");
        mini.hideMessageBox(messageid);
        return false;
    }
    var messageid = mini.loading("正在玩命下载中", "下载中");
    $.ajax({
        url: "QpDownLoad",
        type: "get",
        async: true,
        data: { id: id },
        cache: false,
        timeout: 10000,
        success: function (text) {
            result = text;

            var json = mini.decode(result);
            var message = json.DESCRIPTION;
            var status = json.STATUS;
            var downloadMsg = (2 - parseInt(fnGetQpDownloadCount(id))) + "次下载机会！请慎用！";
            if (status == 1) {
                mini.hideMessageBox(messageid);
                mini.showMessageBox({
                    showModal: false,
                    width: 250,
                    title: "下载成功,还剩" + downloadMsg,
                    message: message,
                    buttons: [],
                    iconCls: "mini-messagebox-ok",
                    timeout: 3000
                });

                var existZhiDanInfoData = SetZhiDan();
                var prefix = mini.get("hidtransport_way").getValue();//获取海陆空前缀
                if (existZhiDanInfoData == 0 && prefix == "02") {
                    SaveZDQPdownload(id);
                    //var operator = [{ id: '', t_main_id: id, operator: empId, operator_type: 102 }];
                    //fnSaveData('t_mains_operator', operator, '');// 操作记录
                }
                var data = new Object();
                data.id = id;
                data.operator_type = 2;
                SetData(data);
                //---------下载成功更新分割表数据------------
                var accompanydata = addt_main_id(accompany_details, id);
                var mainsSplitData = fnSetMainsSplit(id, accompanydata);
                fnSaveMainsSplits(mainsSplitData);
                //----------下载成功更新分割表数据-----------
            } else {
                if (message == "null" || message == null || message == "undefined") {
                    message = "qp繁忙，请稍后再试！";
                }
                mini.hideMessageBox(messageid);
                mini.showMessageBox({
                    showModal: false,
                    width: 250,
                    title: "下载失败",
                    message: message,
                    buttons: ["ok"],
                    iconCls: "mini-messagebox-warning"
                });
            }
            mini.hideMessageBox(messageid);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            if (textStatus === "timeout") {
                mini.alert("QP繁忙请稍后再试");
            } else {
                alert(jqXHR.responseText);

            }
            mini.hideMessageBox(messageid);

        }
    });
}

//获取下载成功次数 add by zengtongchun 2016-12-01
function fnGetQpDownloadCount(id) {
    var data = fnGetData("v_t_qpservice_call_log", "qp_status='成功' and call_mother_name='qpreturn' and t_main_id=" + id).data;
    return data.length;
}
//下载成功后更新分割表的字符串
function fnSaveMainsSplits(data) {
    var json = mini.encode(data);
    $.ajax({
        url: "/extendpage/action/datasave.aspx?entity=t_mains_splits&flag=1&action=update",
        type: "post",
        data: { data: json },
        cache: false,
        success: function (text) {
            console.log("下载更新数据了！");
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert("Error" + jqXHR.responseText);
        }
    });
}

/**********************************
* add by zhongxx 2016-08-31  下载成功后添加制单步骤
**************************************/
function SaveZDQPdownload(id) {
    $.ajax({
        url: "SaveZDQPdownload",
        type: "get",
        async: false,
        data: { id: id },
        cache: false,
        success: function (result) {
            //mini.alert(result);
        },
        error: function (jqXHR, textStatus, errorThrown) {
        }
    });
}

/**********************************
* add by zhanyong 2015-06-03  平台
**************************************/
function PlatForm() {
    var shipState = mini.get("chkchange_yn").getValue();//改船状态
    if (fnIsContainerChange() > 0 && shipState == "0") {
        mini.alert("集装箱已对碰港保费，要操作请联系财务处理！");
        return;
    }
    var id = mini.get("id").getValue();

    /*****************单据类型 如果是出口，取流水号，其它 取提运单号 Edit by zhuhy 2015-06-30 begin***********************/
    var serial_no = description == "Export" ? mini.get("txtserial_no").getValue() : mini.get("txtcabin_no").getValue();
    /*****************单据类型 如果是出口，取流水号，其它 取提运单号 Edit by zhuhy 2015-06-30 end***********************/
    var port_no = mini.get("txtport_no").getValue();
    if (port_no == null || port_no == "") {
        mini.alert("请填写申报口岸");
        return false;
    }
    if (id == null || id == "" || serial_no == "" || serial_no == null) {
        mini.alert("请先保存报关单");
        return false;
    }

    //判断平台配置是否正确 add by zengtongchun 2016-01-19
    var message = mini.loading("正在获取平台数据中", "正在获取平台数据中");
    $.ajax({
        url: "../../CustomsClearance/CheckPlatFormSet",
        type: "get",
        async: true,
        data: { imgcode: "", id: id, serial_no: serial_no, port_no: port_no },
        timeout: 10000,
        cache: false,
        success: function (text) {
            if (text == "1") {//配置都ok
                CheckPlatformLogin(id, serial_no, port_no, shipState);
            } else {
                mini.alert(text);
            }
            mini.hideMessageBox(message);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            if (textStatus === "timeout") {
                mini.alert("取数超时，请确认网路平台打开是否正常！");
            } else {
                alert(jqXHR.responseText);
            }
            mini.hideMessageBox(message);
        }
    });
}

//获取平台信息 add by zengtongchun 2016-01-19
function CheckPlatformLogin(id, serial_no, port_no, shipState) {
    if (port_no == "5304") {
        InputLoginImage(id, serial_no, port_no, shipState);
        return false;
    }
    //判断是否登录 add by zengtongchun 2015-11-11
    $.ajax({
        url: "../../CustomsClearance/GetPlatFormInfo",
        type: "get",
        async: false,
        data: { imgcode: "", id: id, serial_no: serial_no, port_no: port_no, shipState: shipState },
        cache: false,
        success: function (text) {
            var msgData = mini.decode(text);
            if (msgData.Status == 2) {//异常
                alert(msgData.MessageInfos);
                return;
            }
            if (msgData.Status == 0) {//普通提示
                alert(msgData.MessageInfos);
                return;
            }
            if (msgData.Status == 1) {//成功
                if (msgData.SaveMainsMsg == null) {//登录平台
                    alert(msgData.MessageInfos);
                    InputLoginImage(id, serial_no, port_no, shipState);
                    return;
                }
                if (msgData.SaveMainsMsg.length > 0) {
                    //取数消息提示
                    var msg = "";
                    Enumerable.From(msgData.SaveMainsMsg).ForEach(function (i) {
                        msg += i.MessageInfos + "\n";
                    });
                    alert(msg);
                }
            }
            var data = new Object();
            data.id = mini.get("id").getValue();
            data.serial_no = serial_no;
            data.shipState = shipState;
            data.operator_type = 3;
            SetData(data);
            //---------下载成功更新分割表数据------------
            var accompanydata = addt_main_id(accompany_details, data.id);
            var mainsSplitData = fnSetMainsSplit(data.id, accompanydata);
            fnSaveMainsSplits(mainsSplitData);
            //----------下载成功更新分割表数据-----------
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert(jqXHR.responseText);
        }
    });
}

//输入验证码登录 add by zengtongchun 2015-11-11
function InputLoginImage(id, serial_no, port_no, shipState) {
    mini.open({
        url: "../../CustomsClearance/LoginImage?serial_no=" + serial_no + "&port_no=" + port_no + "&id=" + id,
        title: "请输入验证码",
        width: 400,
        height: 100,
        onload: function () {
            var iframe = this.getIFrameEl();
            var data = new Object();
            data.id = id;
            data.serial_no = serial_no;
            data.port_no = port_no;
            data.shipState = shipState;
            iframe.contentWindow.SetData(data);
        },
        ondestroy: function (action) {
            var data = new Object();
            data.id = mini.get("id").getValue();
            data.serial_no = serial_no;
            data.operator_type = 3;
            data.port_no = port_no;
            mini.get("autshipper_name").focus();
            SetData(data);
        }
    });
}

/**********************************
* add by zhanyong 2015-06-15   商检解锁
**************************************/
function fnCommodityInspectionUnLock() {
    var id = mini.get("id").value; //cbtype 报关单类型（进，出口）
    $.ajax({
        url: "CommodityInspectionUnLock",
        type: "get",
        async: false,
        data: { id: id },
        cache: false,
        success: function (result) {
            mini.alert(result);
        },
        error: function (jqXHR, textStatus, errorThrown) {
        }
    });
}

function fnCommodityInspection() {
    var id = mini.get("id").value; //cbtype 报关单类型（进，出口）
    $.ajax({
        url: "CommodityInspection",
        type: "get",
        async: false,
        data: { id: id },
        cache: false,
        success: function (result) {
            mini.alert(result);
        },
        error: function (jqXHR, textStatus, errorThrown) {
        }
    });
}

/**********************************
* add by zhuhy 2015-06-17   单据复制
**************************************/
function fnCoppy() {
    $.ajax({
        url: "Copy",
        type: "get",
        data: { id: id },
        cache: false,
        success: function (text) {
            if (text > 0) {
                alert("复制成功！");
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert(jqXHR.responseText);
        }
    });
}

/**********************************
* add by zhuhy 2015-06-17   单据粘贴
**************************************/
function fnPaste() {
    showPaste();
}
function showPaste() {
    var editWindow = mini.get("editWindow");
    editWindow.show();
    var form = new mini.Form("#editform");
    form.clear();
    form.loading();
    form.unmask();
}
function fnOK() {
    $.ajax({
        url: "Paste",
        type: "get",
        cache: false,
        success: function (text) {
            var result = mini.decode(text);
            var data = result.Data;
            data = mini.decode(data);
            var t_mains = mini.decode(data.t_mains)[0];
            var t_check_statuses = mini.decode(data.t_check_statuses);
            var form = new mini.Form("#form1");
            var costinfo = form.getData();
            t_mains = jQuery.extend(t_mains, t_check_statuses); //合并 报关单主表，查验信息
            t_mains = jQuery.extend(costinfo, t_mains); //合并 报关单主表，费用信息
            var t_goods_details = mini.decode(data.t_goods_details);
            var t_details = mini.decode(data.t_details);
            var gridCount = mini.get("datagrid1"); //集装箱表体

            if (mini.get("rbl").getValue() == "1") {
                //报关单头
                PasteBaoGuanHead(t_mains);
            }
            else if (mini.get("rbl").getValue() == "2") {
                //商品信息
                PasteGoodsInfo(t_goods_details);
            }
            else if (mini.get("rbl").getValue() == "3") {
                //报关单头
                PasteBaoGuanHead(t_mains);
                //商品信息
                PasteGoodsInfo(t_goods_details);
            }
            else if (mini.get("rbl").getValue() == "4") { //长安标致雪铁龙汽车有限公司

                if (gridCount.data.length > 0) {  //粘贴操作   如果有数据先删除原有数据 再粘贴
                    if (fnIsContainerChange() > 0) {
                        mini.alert("集装箱已对碰港保费，要操作请联系财务处理！");
                        return;
                    }
                    gridCount.clearRows();
                    fnSaveData("t_details", gridCount.data, "delete");
                }

                //全部
                PasteBaoGuanHead(t_mains);
                //商品信息
                PasteGoodsInfo(t_goods_details);
                //集装箱表体
                PasteDetails(t_details);
            }

        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert(jqXHR.responseText);
        }
    });
    mini.get("editWindow").hide();
}
//黏贴报关单头 add by zengtongchun 2016-02-25
function PasteBaoGuanHead(t_mains) {
    /**************************设置页面的 autocomplate 控件的值 begin************************/
    //mini.get("autport_name").setText(t_mains.port_name); //出口口岸
    //mini.get("autport_name").setValue(t_mains.port_no); //出口口岸
    // mini.get("txtport_no").setValue(t_mains.port_no);   //出口口岸
    //mini.get("autapply_port_no").setText(t_mains.apply_port_name); //申报口岸
    // mini.get("autapply_port_no").setValue(t_mains.apply_port_no);
    mini.get("txtrecords_no").setValue(t_mains.records_no);//备案号
    if (t_mains.transport_way == "02") {
        mini.get("autshipper_name").setText(t_mains.shipper_name); //经营单位
        mini.get("autshipper_name").setValue(t_mains.shipper_name); //经营单位
        mini.get("txtshipper_no").setValue(t_mains.shipper_no);
        //mini.get("autconsignee_name").setText(t_mains.consignee_name); //发货单位
        mini.get("autconsignee_name").setValue(t_mains.consignee_name); //发货单位
        mini.get("txtconsignee_no").setValue(t_mains.consignee_no);
    }


    //mini.get("auttransmode_no").setText(t_mains.transmode_name); //运输方式
    //mini.get("auttransmode_no").setValue(t_mains.transmode_no); //运输方式
    //mini.get("txttransname").setValue(t_mains.transname); //运输工具
    //mini.get("txtcabin_no").setValue(t_mains.cabin_no);   //提运单号

    mini.get("auttrade_no").setText(t_mains.trade_name); //贸易方式
    mini.get("auttrade_no").setValue(t_mains.trade_no); //贸易方式
    mini.get("autimposemode_no").setText(t_mains.imposemode_name); //征免性质
    mini.get("autimposemode_no").setValue(t_mains.imposemode_no); //征免性质

    var cmbdrawback_no = mini.get("cmbdrawback_no");
    cmbdrawback_no = cmbdrawback_no == null ? "" : cmbdrawback_no.setValue(t_mains.drawback_no);//退税

    var autremitmode_no = mini.get("autremitmode_no");
    if (autremitmode_no != null) {
        mini.get("autremitmode_no").setText(t_mains.remitmode_name); //结汇方式
        mini.get("autremitmode_no").setValue(t_mains.remitmode_no); //结汇方式
    }
    mini.get("txtlicence_no").setValue(t_mains.licence_no);  //许可证号
    mini.get("autstart_country_no").setText(t_mains.start_country_name); //运抵国
    mini.get("autstart_country_no").setValue(t_mains.start_country_no); //运抵国
    mini.get("autloadport_no").setText(t_mains.loadport_name); //指运港
    mini.get("autloadport_no").setValue(t_mains.loadport_no); //指运港

    mini.get("auttrade_country_no").setText(t_mains.trade_country_name); //贸易国(地区)
    mini.get("auttrade_country_no").setValue(t_mains.trade_country_no); //贸易国(地区)

    mini.get("autend_country_no").setText(t_mains.end_country_name); //境内货源地
    mini.get("autend_country_no").setValue(t_mains.end_country_no); //境内货源地
    mini.get("autbargainmode_no").setText(t_mains.bargainmode_name); //成交方式
    mini.get("autbargainmode_no").setValue(t_mains.bargainmode_no); //成交方式
    mini.get("txtcontract_no").setValue(t_mains.contract_no); //合同协议号
    mini.get("txtmark").setValue(t_mains.mark);//标记唛码
    mini.get("autpack_no").setText(t_mains.pack_name); //包装方式
    mini.get("autpack_no").setValue(t_mains.pack_no); //包装方式
    //报关单类型
    mini.get("autentry_type").setText(t_mains.entry_typename);
    mini.get("autentry_type").setValue(t_mains.entry_type);

    //运费
    mini.get("autfreightmode_no").setText(t_mains.freightmode_name);
    mini.get("autfreightmode_no").setValue(t_mains.freightmode_no);
    mini.get("autfreight_currency_no").setText(t_mains.freight_currency_name);
    mini.get("autfreight_currency_no").setValue(t_mains.freight_currency_no);
    //保费
    mini.get("autsubscribemode_no").setText(t_mains.subscribemode_name);
    mini.get("autsubscribemode_no").setValue(t_mains.subscribemode_no);
    mini.get("autsubscribe_currency_no").setText(t_mains.subscribe_currency_name);
    mini.get("autsubscribe_currency_no").setValue(t_mains.subscribe_currency_no);
    //杂费
    mini.get("autincidentalmode_no").setText(t_mains.incidentalmode_name);
    mini.get("autincidentalmode_no").setValue(t_mains.incidentalmode_no);
    mini.get("autincidental_currency_no").setText(t_mains.incidental_currency_name);
    mini.get("autincidental_currency_no").setValue(t_mains.incidental_currency_no);

    /**************************设置页面的 autocomplate 控件的值 end************************/
}
//黏贴报关单商品信息 add by zengtongchun 2015-02-25
function PasteGoodsInfo(t_goods_details) {
    var nowNum = mini.get("datagrid2").data.length;
    for (var i = 0, l = t_goods_details.length; i < l; i++) {
        nowNum++;
        var goodsTemp = t_goods_details[i];
        var newRow = {
            id: '',
            num_no: nowNum,
            item_no: goodsTemp.item_no,
            goods_no: goodsTemp.goods_no,
            goods_name: goodsTemp.goods_name,
            goods_spec: goodsTemp.goods_spec,
            ver_no: goodsTemp.ver_no,
            amount: goodsTemp.amount,
            final_country_no: goodsTemp.final_country_no,
            final_country_name: goodsTemp.final_country_name,
            amount02: goodsTemp.amount02,
            unit_name: goodsTemp.unit_name,
            unit_no: goodsTemp.unit_no,
            unit02_no: goodsTemp.unit02_no,
            unit03_no: goodsTemp.unit03_no,
            unit02_name: goodsTemp.unit02_name, amount03: goodsTemp.amount03,
            unit03_name: goodsTemp.unit03_name, country_no: goodsTemp.country_no,
            country_name: goodsTemp.country_name, sum: goodsTemp.sum,
            price: goodsTemp.price, currency_no: goodsTemp.currency_no,
            currency_name: goodsTemp.currency_name, impose_no: goodsTemp.impose_no,
            impose_name: goodsTemp.impose_name
        };
        mini.get("datagrid2").addRow(newRow);
    }
}


//黏贴报关单商品信息 add by 钟星星 2016-05-18
function PasteDetails(t_details) {
    var nowNum = mini.get("datagrid1").data.length;
    for (var i = 0, d = t_details.length; i < d; i++) {
        nowNum++;
        var detailsTemp = t_details[i];
        var newRow = {
            id: '',
            num_no: nowNum,
            container_type_no: detailsTemp.container_type_no,
            t_main_id: detailsTemp.t_main_id,

            container_no: detailsTemp.container_no,
            fee_type: detailsTemp.fee_type,
            fee_yn: detailsTemp.fee_yn,
            seal_no: detailsTemp.seal_no,
            apply_cost: detailsTemp.apply_cost,

            scan_cost: detailsTemp.scan_cost,
            check_yn: detailsTemp.check_yn,
            check_cost: detailsTemp.check_cost,
            check_id: detailsTemp.check_id,
            check_dt: detailsTemp.check_dt,
            check01_yn: detailsTemp.check01_yn,

            check01_cost: detailsTemp.check01_cost,
            check01_id: detailsTemp.check01_id, check01_dt: detailsTemp.check01_dt,
            wharf_cost: detailsTemp.wharf_cost, wharf_id: detailsTemp.wharf_id,
            wharf_yn: detailsTemp.wharf_yn, wharf_dt: detailsTemp.wharf_dt,
            audit_yn: detailsTemp.audit_yn, audit_id: detailsTemp.audit_id,
            audit_dt: detailsTemp.audit_dt,

            protect_cost: detailsTemp.protect_cost,
            protect_dt: detailsTemp.protect_dt,
            protect_id: detailsTemp.protect_id,
            protect_yn: detailsTemp.protect_yn,
            audit2_yn: detailsTemp.audit2_yn,
            audit2_id: detailsTemp.audit2_id, audit2_dt: detailsTemp.audit2_dt,
            fc_yn: detailsTemp.fc_yn, fc_dt: detailsTemp.fc_dt,
            fc_cost: detailsTemp.fc_cost, pt_yn: detailsTemp.pt_yn,
            hgtz_dt: detailsTemp.hgtz_dt, sjtz_dt: detailsTemp.sjtz_dt,
            hgdc_dt: detailsTemp.hgdc_dt, gjdc_dt: detailsTemp.gjdc_dt,
            hgwz: detailsTemp.hgwz,


            gjwz: detailsTemp.gjwz,
            hgwc_dt: detailsTemp.hgwc_dt,
            sanitate_yn: detailsTemp.sanitate_yn,
            order_no: detailsTemp.order_no,
            hgcy_name: detailsTemp.hgcy_name,
            wharf_newid: detailsTemp.wharf_newid, protect_newid: detailsTemp.protect_newid,
            loadport_dt: detailsTemp.loadport_dt,


        };
        mini.get("datagrid1").addRow(newRow);
    }
}

/**********************************
* add by zhuhy 2015-06-18   客户要求
**************************************/
function fnRequirements(isview) {
    var customer_id = mini.get("hidcustomer_id").getValue();
    mini.open({
        url: "/CustomsClearance/ClientRequirements?isview=" + isview,
        title: "新增客户要求", width: 800, height: 460,
        onload: function () {
            var iframe = this.getIFrameEl();
            var data = { customer_id: customer_id, empId: empId };
            iframe.contentWindow.SetData(data);
        },
        ondestroy: function (action) {
        }
    });
}

/*********************************************
* add by zhongxx 2015-12-03  报关单查询  F2 开始
**************************************/
function fnOperator(id) {
    var way = mini.get("hidtransport_way").getValue();
    var des = fnGetEntityInstance("v_data_base_dictionary_detail", "code='bg_kouanleixing' and value='" + way + "'");

    var prefix = "";
    if (des != null) {
        prefix = des.description;
    }
    if (id == 2) {
        mini.open({
            url: "../CustomsClearance/BgQuickQuery",
            title: "报关单查询",
            width: 400,
            height: 225,
            onload: function () {
                var iframe = this.getIFrameEl();
                var data = { prefix: prefix };

                //调用弹出页面方法进行初始化
                iframe.contentWindow.SetData(data);
            },    //弹出页面加载完成
            ondestroy: function (action) {
                if (action=="ok") {
                    var iframe = this.getIFrameEl();
                    //获取选中、编辑的结果
                    var data = iframe.contentWindow.GetData();
                    //if (data.id != 0) {
                    //    SetData({ id: data.id });
                    //}
                    
                }
            }
        });
        return;
    }
    if (id == 3) {
        mini.open({
            url: "../CustomsClearance/BgCheck",
            title: "复核",
            width: 400,
            height: 225,
            onload: function () {       //弹出页面加载完成
                var iframe = this.getIFrameEl();
                var data = { prefix: mini.get("hidPrefix").getValue() };
                //调用弹出页面方法进行初始化
                iframe.contentWindow.SetData(data);
            },
            ondestroy: function (action) {
                //   SetData({ id: setID, barcode_no: barcode_no });
            }
        });
    }
    if (id == 4) {
        mini.open({
            url: "../CustomsClearance/BgLYQuickQuery",
            title: "陆运快速调单",
            width: 400,
            height: 225,
            onload: function () {       //弹出页面加载完成
                var iframe = this.getIFrameEl();
                //var way = mini.get("hidtransport_way").getValue();
                //var prefix = "";
                //if (way == "02") {
                //    prefix = "LY";
                //}
                //else if (way == "01") {
                //    prefix = "HY";
                //}
                var data = { prefix: prefix };

                //调用弹出页面方法进行初始化
                iframe.contentWindow.SetData(data);

            },
            ondestroy: function (action) {

            }
        });
    }

}

/***********************************************
        * add by zhongxx 2015-12-03  报关单查询  F2 结束
       **************************************/
//获取cookie值 add by zengtongchun 2016-08-30
function fnSetCookie(cookieId, className, text) {
    if (text != "") {
        $("#" + cookieId).html(text);
        $("#" + cookieId).parent().parent().next().hide();
        $.ajax({
            url: "/CustomsClearance/SetCookieExport",
            type: "post",
            data: { className: className, text: text, cookieId: cookieId },
            cache: false,
            success: function (backData) {


            },
            error: function (jqXHR, textStatus, errorThrown) {
                // alert("Error" + jqXHR.responseText);
            }
        });
    }

}
//判断商品编码是否在本库存在add by zengtongchun 2016-09-19
function fnGetGoodsInfo() {
    var msg = "";
    var nowData = mini.get("datagrid2").getData();
    var nowArray = Enumerable.From(nowData).Select("$.goods_no").Distinct().ToArray();
    var goodsNo = nowArray.join("','");
    if (nowData.length > 0) {
        goodsNo = "'" + goodsNo + "'";
        var oldData = fnGetData("v_t_goods_code", "code_ts in(" + goodsNo + ")").data;
        for (var i = 0; i < nowArray.length; i++) {
            var exist = 0;
            for (var j = 0; j < oldData.length; j++) {
                if (nowArray[i] == oldData[j].code_ts) {
                    exist = 1;
                    break;
                }
            }
            if (exist == 0) {
                if (msg == "") {
                    msg += "商品编码" + nowArray[i];
                }
                else {
                    msg += "," + nowArray[i];
                }
            }
        }
        if (msg != "") {
            msg += "不存在,请核实！";
        }
    }

    return msg;
}
//判断商品编码是否在本库存规格add by zengtongchun 2016-09-19
function fnGetGoodsElements() {
    var msg = "";
    var nowData = mini.get("datagrid2").getData();
    var nowArray = Enumerable.From(nowData).Select("$.goods_no").Distinct().ToArray();
    for (var i = 0; i < nowArray.length; i++) {
        var data = fnGetData("t_goods_elements", "goods_no='" + nowArray[i] + "'").data;
        if (data.length <= 0) {
            if (msg == "") {
                msg += "商品编码" + nowArray[i];
            }
            else {
                msg += "," + nowArray[i];
            }
        }
    }
    if (msg != "") {
        msg += "规格不存在,请核实！";
    }
    return msg;
}

/**********************************
* add by zengtongchun 2015-12-15   打印函数集开始            ********************************************************************
**************************************/
//打印方法 grfName 报表文件名称 title打印标题

function fnPrintCommon(grfName, title, self) {

    var way = mini.get("hidtransport_way").getValue();

    //var exist = fnCheckQpRecord();
    //var applyNo = mini.get("txtapply_no").getValue();
    //if (exist == 0 && grfName == "apply_ys" && applyNo == "" && way == "02") {
    //    mini.alert("不是最新上传或者下载的数据不允许打印！");
    //    return;
    //}
    var id = mini.get("id").getValue(); //当前单号id
    if (grfName == "apply_ys") {
        var msg = fnGetGoodsInfo();
        if (msg != "") {
            mini.alert(msg);
            return;
        }
        msg = fnGetGoodsElements();
        if (msg != "") {
            mini.alert(msg);
            return;
        }
    }

    var text = "";
    if (self != null && self != "") {
        text = self.defaultText;
    }
    var hidDeclareId = mini.get("hiddeclare_id").getValue();
    if (grfName == "apply_myht_zxjk" && (mini.get("autcustomer_name").getText() != "深圳中兴" || hidDeclareId != 2)) {
        mini.alert("非深圳中兴进口！没(合同)打印权限！");
        return;
    }
    if ((grfName == "apply_fp_hw" || grfName == "apply_myht_hw" || grfName == "apply_zxd_hw") && mini.get("autcustomer_name").getText() != "深圳华为") {
        mini.alert("客户不是华为！没打印权限！");
        return;
    }
    var applyDt = "";
    if (grfName == "wts") {
        applyDt = mini.formatDate(mini.get("txtapply_dt").getValue(), "yyyy-MM-dd");
    }
    fnSetCookie("printText", grfName, text);

    var dataUrl = "../BusZhiDan/Exppost?id=" + id;
    window.open("../../ReportList/PrintTmp.aspx?dataUrl=" + dataUrl + "&grfName=" + grfName + "&title=" + title + "&applyDt=" + applyDt);
}

function fnPrintWord(viewName, self) {
    //var exist = fnCheckQpRecord();
    //if (exist == 0 && viewName == "apply_ys") {
    //    mini.alert("不是最新上传或者下载的数据不允许打印！");
    //    return;
    //}
    if (viewName == "MainsView") {
        var msg = fnGetGoodsInfo();
        if (msg != "") {
            mini.alert(msg);
            return;
        }
        msg = fnGetGoodsElements();
        if (msg != "") {
            mini.alert(msg);
            return;
        }
    }
    var text = "";
    if (self != null && self != "") {
        text = self.defaultText;
    }
    fnSetCookie("printText", viewName, text);
    var id = mini.get("id").getValue(); //当前单号id
    window.open("/PrintView/" + viewName + "?id=" + id, "", "", "_word");

}

/**********************************
* add by zhuhy 2015-06-18   商品要素打印
**************************************/

function fnPrintys() {
    var datagrid1 = mini.get("datagrid1");
    var id = mini.get("id").getValue(); //当前单号id
    var rows = datagrid1.getData();
    var container = "";
    if (rows.length > 0) {
        container = rows[0]["container_no"];
    }
    var tc = container;
    if (container.length > 0) {
        tc = tc + ',';
    }

    var ac = "";
    if (rows.length > 0) {
        for (i = 0; i < rows.length; i++) {
            ac = ac + rows[i]["accompany_no"] + ',';
        }
    }
    var p = "true"; //是否打印印章
    var reportname = "'apply_ys'"; //打印类型
    window.open("../../ReportList/ReportApply_ys.aspx?id=" + id + "&p=" + p + "&reportname=" + reportname + "&container='" + container + "'&tc=" + tc + "&ac=" + ac);
}

/**********************************
        * add by zhuhy 2015-12-15   打印函数集结束            ********************************************************************
        **************************************/

/**********************************
* add by zhuhy 20160513 【出口】单 商品表体 如果【原产国地区】 为空默认  【中国】
**************************************/
function UpdateGoodsfinal_country_no() {

    // 只有出口做这个动作
    var type = mini.get("hiddeclare_id").getValue();
    if (type != 1) return;
    var goodsgrid = mini.get("datagrid2");
    var goodslist = goodsgrid.data;

    $.each(goodslist, function (index, item) {
        if (item.final_country_no != 142) {
            goodsgrid.updateRow(item, {
                final_country_no: 142,
                final_country_name: "中国"
            });
        }
    });
}
